<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header" class="login-header">
        <span>黑马面经运营后台</span>
      </div>
      <div class="text item">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="用户名" prop="username">
            <el-input
              placeholder="请输入用户名"
              v-model="form.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              v-model="form.password"
              @keyup.enter.native="login"
            ></el-input>
          </el-form-item>
          <el-form-item class="btns">
            <el-button @click="login" :loading="flag">登录</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'login-page',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 11, message: '长度必须是5-11位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{5,11}$/,
            message: '请输入5-11位的字符',
            trigger: 'blur'
          }
        ]
      },
      flag: false
    }
  },
  methods: {
    async login() {
      try {
        this.$refs.form.validate()
        this.flag = true
        const res = await login(this.form)
        // console.log(res)
        this.$store.commit('user/setToken', res.data.token)
        this.flag = false
        this.$message.success('登陆成功！')
        this.$router.push('/')
      } catch (err) {
        // console.log(err)
        this.flag = false
        if (err.response && err.response.status === 400) {
          this.$message.error('用户名或密码错误')
        } else this.$message.error('登陆失败')
      }
    },
    reset() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
$color: #7d6bf8;
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('@/assets/login-bg.svg') no-repeat center center / cover;

  .login-card {
    width: 420px;

    ::v-deep .el-card__header {
      height: 80px;
      background-color: $color;
    }
    .login-header {
      text-align: center;
      font-size: 18px;
      color: #fff;
    }
  }

  .btns {
    text-align: center;
    .el-button:first-child {
      color: #fff;
      background: $color;
    }
  }
}
</style>
